<?php

namespace app\admin\model;

use app\admin\validate\Bbs;
use think\Model;

class Plate extends Model
{
    public function getplatelist($data)
    {
        $result = db("plate")
            ->alias("p")
            ->join("app a", "a.appid=p.appid")
            ->where("p.platename","like","%{$data['platename']}%")
            ->field("p.*,a.appname")
            ->limit($data["limit"])->page($data["page"])
            ->order($data["sort"], $data["sortOrder"])
            ->select();
        $count = db("plate")
            ->alias("p")
            ->join("app a", "a.appid=p.appid")
            ->where("p.platename","like","%{$data['platename']}%")
            ->field("p.*,a.appname")
            ->count();
        return json(["rows" => $result, "total" => $count]);
    }

    public function addplate($data)
    {
        $validate = new Bbs();
        if(!$validate->scene('addplate')->check($data)){
            return $validate->getError();
        }
        $data["creattime"] = date("Y-m-d H:i:s",time());
        $result = $this->allowField(true)->save($data);
        if($result > 0){
            return 1;
        }else{
            return "服务器错误";
        }
    }

    public function getplateinfo($id)
    {
        $result = $this->where("id",$id)->find();
        $result["appname"] = App::get($result["appid"]) != Null ? App::get($result["appid"])["appname"] : "暂无此app";
        return $result;
    }

    public function editplate($data)
    {
        $validate = new Bbs();
        if(!$validate->scene('updateplate')->check($data)){
            return $validate->getError();
        }
        $id = $data["id"];
        unset($data["id"]);
        $result = $this->allowField(true)->save($data,["id"=>$id]);
        return 1;
    }

    public function deleteplate($id)
    {
        if(!is_array($id)){
            return "服务器错误";
        }
        foreach($id as $key=>$value){
            $this->where("id",$value)->delete();
        }
        return 1;
    }
}
